<template>
  <a-card :bordered="false">
    <template #title>
      <a-space size="small">
        <LeftCircleTwoTone style="font-size: 20px" @click="$emit('showTable')"></LeftCircleTwoTone>
        {{ props.recode.id ? '编辑 ' : '添加' }}
      </a-space>
    </template>

    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 8 }"
      autocomplete="off"
      @finish="onFinish"
    >
      <a-form-item label="用户名" name="userName" :rules="[{ required: true, message: '请输入用户名!' }]">
        <a-input v-model:value="formState.userName" allow-clear />
      </a-form-item>
      <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
        <a-input v-model:value="formState.password" allow-clear />
      </a-form-item>

      <a-form-item label="角色" name="role" :rules="[{ required: true, message: '请选择角色!' }]">
        <a-select
          ref="select"
          v-model:value="formState.role"
          style="width: 120px"
          placeholder="请选择角色"
          :disabled="formState.userName !== 'admin' && formState.id"
        >
          <a-select-option :value="0">普通用户</a-select-option>
          <a-select-option :value="1">管理员</a-select-option>
          <a-select-option :value="9">超级管理员</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="分区键gcId" name="gcId" :rules="[{ required: true, message: '请输入分区键gcId!' }]">
        <a-input v-model:value="formState.gcId" allow-clear />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-space size="large">
          <a-button type="primary" html-type="submit">{{ props.recode.id ? '更新' : '添加' }}</a-button>
          <a-button type="primary" @click="$emit('showTable')">返回</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
import { LeftCircleTwoTone } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { User } from '@/api/user/user';
import * as userApi from '@/api/user/user';

const props = defineProps<{
  recode: User;
}>();

const emit = defineEmits<{
  (e: 'showTable'): void;
}>();

const formState: User = reactive(props.recode);

function onFinish() {
  console.log('Success:', formState);
  userApi.userSave(formState).then(jsonResult => {
    if (!jsonResult) {
      return;
    }
    emit('showTable');
    message.success(formState.id ? '更新成功！' : '添加成功');
  });
}
</script>

<style lang="less" scoped></style>
